package nobu.nakata.nfcfare.resource.mapper;

import java.util.Calendar;

import net.sf.jsr107cache.Cache;
import nobu.nakata.nfcfare.resource.builder.SuicaUsageResouceItemBuilder;
import nobu.nakata.nfcfare.resource.builder.SuicaUsageResouceItemBuilder.SuicaUsageResouceItemBuilderException;
import nobu.nakata.nfcfare.resource.item.ISuicaUsageResourceItem;

public class SuicaUsageResourceMapper {
	private Cache cache;
	private String trainBaseUrl;
	private String busBaseUrl;
	private Calendar calendar;
	private SuicaUsageResouceItemBuilder _itemBuilder;
	
	public SuicaUsageResourceMapper(Cache cache, String trainBaseUrl, String busBaseUrl, Calendar calendar) {
		this.cache			= cache;
		this.trainBaseUrl	= trainBaseUrl;
		this.busBaseUrl		= busBaseUrl;
		this.calendar		= calendar;
	}
	
	
	public ISuicaUsageResourceItem makeByUsageData(String usageData) {
		String cacheKey = makeCacheKey(usageData);
		ISuicaUsageResourceItem stored = (ISuicaUsageResourceItem) cache.get(cacheKey);
		if (stored != null)
			return stored;
		stored = loadMakeByUsageData(usageData);
		cache.put(cacheKey, stored);
		return stored;
	}
	
	private ISuicaUsageResourceItem loadMakeByUsageData(String usageData) {
		try {
			SuicaUsageResouceItemBuilder itemBuilder = makeBuilder();
			itemBuilder.fromUsageData(usageData);
			return _itemBuilder.getItem();
		} catch (SuicaUsageResouceItemBuilderException e) {
			return null;
		}
	}
	private SuicaUsageResouceItemBuilder makeBuilder() {
		if (_itemBuilder == null)
			_itemBuilder = new SuicaUsageResouceItemBuilder(
				trainBaseUrl, busBaseUrl, calendar);
		return _itemBuilder;
	}
	
	
	private static final String KIND = ISuicaUsageResourceItem.class.getSimpleName();
	private static String makeCacheKey(String usageData) {
		return KIND + ":" + usageData;
	}
}
